<template>
  <div class="login">
    <el-form
      class="login-form"
      label-position="top"
      ref="form"
      :model="formMessage"
      :rules="formRules"
      label-width="80px">
      <el-form-item label="手机号" prop="phone">
        <el-input type="text" v-model="formMessage.phone" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formMessage.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-btn" :loading="loading" @click="handleSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Form } from 'element-ui'
import { userLogin } from '@/services/front'
import { ACCESS_TOKEN, REFRESH_TOKEN } from '@/utils/constants'
import { setCookies } from '@/utils/cookie'
import { getFormDataParams } from '@/utils/common'

@Component
export default class LoginPage extends Vue {
  private formMessage: any = {
    phone: '',
    password: ''
  }

  private loading = false

  private formRules: any = {
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
    ]
  }

  async handleSubmit () {
    await (this.$refs.form as Form).validate()
    const params = getFormDataParams(this.formMessage)
    try {
      this.loading = true
      const data: any = await userLogin(params)
      console.log(data)
      if (data.state === 1) {
        const content = JSON.parse(data.content)
        setCookies(ACCESS_TOKEN, content.access_token)
        setCookies(REFRESH_TOKEN, content.refresh_token)
        await this.$router.push({
          name: 'home'
        })
      } else {
        window.alert(data.message)
      }
    } catch (e) {
      console.error(e)
    } finally {
      this.loading = false
    }
  }
}
</script>

<style scoped lang="scss">
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-form {
    width: 300px;
    background: #fff;
    padding: 20px;
    border-radius: 5px;
  }
  .login-btn {
    width: 100%;
  }
}
</style>
